<template>
  <div ref="wrapper" class="wrapper">
    <slot></slot>
  </div>
</template>

<script type="text/ecmascript-6">
  import BScroll from 'better-scroll'

  export default {
    props: {
      probeType: {
        type: Number,
        default: 1
      },
      click: {
        type: Boolean,
        default: true
      },
      listenScroll: {
        type: Boolean,
        default: false
      },
      /**
       * 是否派发滚动到底部的事件，用于上拉加载
       */
      pullup: {
        type: Boolean,
        default: false
      }
    },
    mounted () {
      setTimeout(() => {
        this._initScroll()
      }, 20)
    },
    methods: {
      _initScroll () {
        if (!this.$refs.wrapper) {
          return
        }

        this.scroll = new BScroll(this.$refs.wrapper, {
          probeType: this.probeType,
          click: this.click,
          pullUpLoad: {
            threshold: 50
          },
          pullDownRefresh: {
            threshold: 60,
            stop: 40
          }
        })

        if (this.listenScroll) {
          this.scroll.on('scroll', (pos) => {
            this.$emit('scroll', pos, this.scroll.maxScrollY)
          })
          this.scroll.on('scrollEnd', (pos) => {
            this.$emit('scrollEnd', pos, this.scroll.maxScrollY)
          })
          // 上拉加载
          this.scroll.on('pullingUp', () => {
            this.$emit('pullingUp')
          })
          // 下拉刷新
          this.scroll.on('pullingDown', () => {
            this.$emit('pullingDown')
          })
        }

        // 是否派发滚动到底部事件，用于上拉加载
        if (this.pullup) {
          this.scroll.on('scrollEnd', (pos) => {
            // 滚动到底部
            if (this.scroll.y <= (this.scroll.maxScrollY + 50)) {
              this.$emit('scrollToEnd', pos, this.scroll.maxScrollY)
            }
          })
        }
      },
      enable () {
        this.scroll && this.scroll.enable()
      },
      disable () {
        this.scroll && this.scroll.disable()
      },
      refresh () {
        this.scroll && this.scroll.refresh()
      },
      // 上拉加载数据结束后调用
      finishPullUp () {
        this.scroll && this.scroll.finishPullUp()
      },
      // 下拉刷新数据加载完毕后调用
      finishPullDown () {
        this.scroll && this.scroll.finishPullDown()
      },
      scrollTo () {
        this.scroll && this.scroll.scrollTo.apply(this.scroll, arguments)
      },
      scrollBy () {
        this.scroll && this.scroll.scrollBy.apply(this.scroll, arguments)
      },
      scrollToElement () {
        this.scroll && this.scroll.scrollToElement.apply(this.scroll, arguments)
      }
    },
    watch: {
      // data () {
      //   setTimeout(() => {
      //     this.refresh()
      //   }, 20)
      // }
    }
  }
</script>
<style lang="scss" scoped>
  .wrapper {
    height: 100%;
    overflow: hidden;
  }
</style>
